fs = require 'fs'
GridStore = require('mongoose').mongo.GridStore
logger = require('./logging').logger

exports.FileStoreUtil = class
  constructor: (fsdb) ->
    @fsdb = fsdb

  uploadFile : (gridfs_id,file_path,file_name,file_type,callback) ->
    cb = (err) ->
      #删除上传文件
      fs.unlink file_path, (unlinkErr) ->
        logger.error(unlinkErr.message || unlinkErr.toString()) if unlinkErr
        callback(err)

    fs.readFile file_path, (err,data) =>
      return cb(err) if err
      gs = new GridStore(@fsdb, gridfs_id, file_name, "w",{content_type:file_type})
      gs.open (err,gs) ->
        return cb(err) if err
        gs.write data, (err,gs) ->
          return cb(err) if err
          gs.close (err) ->
            return cb(err) if err
            cb(null)

  deleteFile : (gridfs_id,cb) ->
    gs = new GridStore(@fsdb, gridfs_id, "r")
    gs.open (err,gs) ->
      return cb(err) if err
      gs.unlink (err) ->
        return cb(err) if err
        cb(null)


  deleteFileByName : (filename,cb)->
    GridStore.unlink @fsdb, filename, (err, gridStore) ->
      cb err

  readFile : (gridfs_id, cb) ->
    gs = new GridStore(@fsdb, gridfs_id, "r")
    gs.open (err,gs) ->
      return cb(err) if err
      cb(null,gs.contentType,gs.filename,gs)